import express from "express";
import { formatRequestQuery, formatResponse } from "../../utils/tools";
import { attachmentManageService } from "../../services/system/attachmentManageService";
import { uploadMiddleware } from "../middlewares/uploadFile";
const router = express.Router();
const queryField = ["name", " code", " url"];

router.post("/", async (req, res) => {
  await attachmentManageService.add(req.body);
  res.send(formatResponse<null>(null, "操作成功"));
});

router.delete("/:id", async (req, res) => {
  const result = await attachmentManageService.delete(req.params.id);
  res.send(formatResponse(result));
});

router.put("/", async (req, res) => {
  const result = await attachmentManageService.update(req.body);
  res.send(formatResponse(result));
});

router.get("/page", async (req, res) => {
  const { query, other } = formatRequestQuery(req.query, queryField);
  const result = await attachmentManageService.findByPage(query.current, query.size, other);
  res.send(formatResponse<typeof result>(result));
});

router.get("/list", async (req, res) => {
  const { other } = formatRequestQuery(req.query, queryField);
  const result = await attachmentManageService.findByList(other);
  res.send(formatResponse<typeof result>(result));
});

router.get("/treeList", async (req, res) => {
  const { other } = formatRequestQuery(req.query, queryField);
  const result = await attachmentManageService.findByTreeList(other);
  res.send(formatResponse<typeof result>(result));
});

router.get("/:id", async (req, res) => {
  const result = await attachmentManageService.findById(req.params.id);
  res.send(formatResponse(result));
});

router.get("/byCode/:code", async (req, res) => {
  const result = await attachmentManageService.findByCode(req.params.code);
  res.send(formatResponse(result));
});

router.post("/import", uploadMiddleware().single("file"), async (req: any, res) => {
  const resp = await attachmentManageService.importData(req.file.path);

  res.send(formatResponse(`成功导入 ${resp} 条数据`));
});

export default router;
